//
//  MTWebViewController.swift
//  MiTao
//
//  Created by zhang qiang on 2018/12/3.
//  Copyright © 2018 DDC. All rights reserved.
//

import UIKit
import SnapKit
import WebKit
import YPNavigationBarTransition
import MBProgressHUD
import RxSwift
import RxCocoa
import DeviceKit
import Moya
import Result
import MTCategory


class MTWWKProcessPool: WKProcessPool {
    class var shared: MTWWKProcessPool {
        struct Static {
            static let instance: MTWWKProcessPool = MTWWKProcessPool()
        }
        
        return Static.instance
    }
}

class MTWebViewController: BaseViewController {
    
    private var paymentType: PayType = .wp
    private var bag = DisposeBag()
    public var skipPageCount: Int = 0
    public var reloadOnViewWillAppear: Bool = false
    public var fullScreen: Bool = false
    public var backToWhereComeFrom: Bool = false
    
    private var paySuccessURLStr: String = ""
    private var isNeedPushSuccess: Bool = false
    private var rightShareJsSource: String = ""
    private var config: MTWkWebViewConfig?
    
    public var readOnlyWebView: WKWebView {
        get {
            return self.web
        }
    }
    
    private lazy var webView: MTWebView = {
        let webView: MTWebView = MTWebView()
        return webView
    }()
    
    
    private var web: WKWebView = WKWebView()
    
    private var loadURL: String = ""
    
    deinit {
        self.webView.delegate = nil
    }
    
    
    internal required override init() {
        super.init()
    }
    
    public convenience init(_ loadURL: String, title: String) {
        self.init(loadURL, config: nil, title: title)
        self.loadURL = loadURL
    }
    
    public convenience init(_ loadURL: String, config: MTWkWebViewConfig? = nil, title: String) {
        self.init(loadURL, config: config, title: title, backToWhereComeFrom: false)
        self.loadURL = loadURL
    }
    
    
    public convenience init(_ loadURL: String, config: MTWkWebViewConfig? = nil, title: String, backToWhereComeFrom: Bool) {
        self.init()
        self.loadURL = loadURL
        self.skipPageCount = 1
        self.fullScreen = false
        self.backToWhereComeFrom = backToWhereComeFrom
        self.navigationItem.title = title
        if config != nil {
            self.config = config
        } else {
            self.config = MTWkWebViewConfig()
//            self.config!.scriptMessageHandlerArray = MTNativeFunction.allNativeFunctions()
            self.config!.isShowScrollIndicator = false
            self.config!.isProgressHidden = false
            self.config!.allowsForwardNavigationGestures = false
            self.config!.allowsBackNavigationGestures = false
            self.config!.allowsSnapShot = false
            self.config!.bounces = false
            self.config!.processPool = MTWWKProcessPool.shared
            self.config!.autoSetNavTitle = false
            
//            let sourceScript =  MTNativeFunction.startScriptSource()
            
//            let userScript: WKUserScript = WKUserScript(source: sourceScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
            
//            self.config!.userScript = userScript
            
            //config.isAllowsBackForwardGestures = false
            webView.webConfig = self.config
            webView.delegate = self
        }
    }
    
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = MainPageBackgroundColor
        self.automaticallyAdjustsScrollViewInsets = false
        self.extendedLayoutIncludesOpaqueBars = self.fullScreen ? false : true
        self.view.addSubview(self.webView)
        
        if self.backToWhereComeFrom {
            backToHomeButton()
        }
        
        self.webView.snp.makeConstraints {
            $0.top.equalToSuperview().offset(StatusBarHeight + (self.fullScreen ? 0 : NavigationBarHeight))
            $0.left.right.equalTo(view)
            $0.bottom.equalTo(self.view).offset(self.hidesBottomBarWhenPushed ? 0 : -TabBarHeight)
        }
        
        self.webView.webloadType(self, .URLString(url: self.loadURL))
        
        backBtn()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.reloadOnViewWillAppear == true {
            //self.showLoading()
            self.webView.webloadType(self, .URLString(url: self.loadURL))
        }
    }
    
    private func backBtn() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_back"), style: .done, target: self, action: #selector(back))
    }
    
    @objc func back() {
        if navigationController!.viewControllers.count > 2 {
            //backAndRefresh("false")
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
}


extension MTWebViewController {
    public func backToHomeButton() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_back"), style: .done, target: self, action: #selector(popToWhereComeFrom))
    }
    
    @objc public func popToWhereComeFrom() {
        //navigationController?.selectHome()
        navigationController?.popToRootViewController(animated: true)
    }
}

extension MTWebViewController: WKWebViewDelegate {
//    //MARK: H5 方法回调
//    public func webViewUserContentController(_ webView: WKWebView, _ scriptMessageHandlerArray: [String], didReceive message: WKScriptMessage) {
//        if message.name == kNativeActionMessage {
//            let messageDict: [String : Any] = message.body as! [String : Any]
//            if messageDict.keys.count == 0 {
//                return
//            }
//            let messageBody: String = messageDict["body"]! as! String
//            let selectorStr: String = self.selectorStrForMessage(message: messageBody) as String
//            let parameters: [String] = self.parametersForMessage(message: messageBody)
//            self.selector(selectorName: selectorStr, parameters: parameters)
//        }
//    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // 如果是跳转一个新页面
        if navigationAction.targetFrame == nil {
            let web: MTWebViewController =
                MTWebViewController(navigationAction.request.url!.absoluteString, title: "")
            navigationController?.pushViewController(web, animated: true)
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }
    
    public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        //debugPrint("开始加载")
//        self.showLoading()
    }
    
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.web = webView
        webView.evaluateJavaScript("document.readyState") { (obj, err) in
            if obj != nil {
                let s: String = obj as! String
                if  s == "complete" || s == "interactive" {
                    
                }
            }
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3, execute: {
//            self.closeLoading()
        })
    }
}


extension MTWebViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return self.fullScreen ? [.hidden] : [.backgroundStyleColor, .backgroundStyleOpaque]
    }
    
    override func yp_navigationBackgroundColor() -> UIColor! {
        return self.fullScreen ? .clear : .white
    }
}
